{% extends 'layout/manage.html' %}
{% load static %}
{% block css %}
<link rel="stylesheet" href="{% static 'tracer/css/file.css' %}">
{% endblock %}
{% block content %}
<div class="container-fluid">
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">
            <div>
                <a href="{% url 'websass:file' project_id=request.tracer.project.id %}">
                    <i class="fa fa-home" aria-hidden="true"></i> 文件库
                </a>

                {% for record in breadcrumb_list %}
                <a href="{% url 'websass:file' project_id=request.tracer.project.id %}?folder={{ record.id }}">
                    <i class="fa fa-angle-right" aria-hidden="true"></i> {{ record.name }}
                </a>
                {% endfor %}
            </div>
            <div class="function">
                <div class="btn btn-primary btn-xs upload" style="position: relative">
                    <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                    <input type="file" multiple name="uploadFile" id="uploadFile">
                </div>
                <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="新建文件夹">
                    <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                </a>
            </div>
        </div>
        <!-- Table -->
        <table class="table">
            <thead>
            <tr>
                <th>名称</th>
                <th>文件大小</th>
                <th>更新者</th>
                <th>更新时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="rowList">
            {% for item in file_object_list %}
            <tr>
                <td>
                    {% if item.file_type == 2 %}
                    <a href="{% url 'websass:file' project_id=request.tracer.project.id %}?folder={{ item.id }}">
                        <i class="fa fa-folder-open-o" aria-hidden="true"></i> {{ item.name }}
                    </a>
                    {% else %}
                    <i class="fa fa-file" aria-hidden="true"></i> <span>{{ item.name }}</span>
                    {% endif %}
                </td>
                <td>
                    {% if item.file_type == 1 %}
                    {{ item.file_size }}
                    {% else %}
                    -
                    {% endif %}
                </td>
                <td>{{item.update_user.username}}</td>
                <td>{{ item.update_datetime }}</td>
                <td>
                    {% if item.file_type == 2 %}
                    <a class="btn btn-default btn-xs"
                       data-toggle="modal"
                       data-target="#addModal"
                       data-whatever="编辑文件夹"
                       data-name="{{item.name}}"
                       data-fid="{{item.id}}">
                        <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                    </a>
                    {% else %}
                    <a href="{%url 'websass:file_download' project_id=request.tracer.project.id file_id=item.id %}"
                       class="btn btn-default btn-xs">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>
                    {% endif %}
                    <a class="btn btn-danger btn-xs"
                       data-toggle="modal"
                       data-fid="{{item.id}}"
                       data-target="#alertModal"
                    >
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
</div>
<!-- Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel"></h4>
            </div>
            <div class="modal-body">
                <form id="form">
                    {% csrf_token %}
                    <input type="text" class="hide" name="fid" id="fid">
                    {% for field in form %}
                    <div class="form-group">
                        <label for="{{ field.id_for_label }}">{{field.label}}</label>
                        {{ field }}
                        <span class="error-msg">{{ field.errors.0 }}</span>
                    </div>
                    {% endfor %}
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                <button id="btnFormSubmit" type="button" class="btn btn-primary">确 定</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="alertModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="alert alert-danger alert-dismissible fade in" role="alert">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                    aria-hidden="true">×</span></button>
            <h4>是否确定删除文件？</h4>
            <p style="padding-top: 20px;padding-bottom: 20px;">文件夹所包含的文件都会被删除掉！</p>
            <p style="text-align: right;">
                <a class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取 消</a>
                &nbsp;
                <button id="btnDelete" type="button" class="btn btn-danger btn-sm">确 定</button>
            </p>
        </div>
    </div>
</div>


<div id="uploadProgress" class="upload-progress hide">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度
        </div>
        <table class="table">
            <tbody id="progressList">
            </tbody>
        </table>
    </div>
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100" style="width:0%">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
        </table>
    </div>
</div>

<div class="hide">
    <table id="rowTpl">
        <tr>
            <td>
                <i class="fa fa-file" aria-hidden="true"></i>

                <span class="name"></span>
            </td>
            <td class="file_size"></td>
            <td class="username"></td>
            <td class="datetime"></td>
            <td>
                <a class="btn btn-default btn-xs download">
                    <i class="fa fa-cloud-download" aria-hidden="true"></i>
                </a>
                <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#alertModal">
                    <i class="fa fa-trash" aria-hidden="true"></i>
                </a>
            </td>
        </tr>
    </table>

    </table>

</div>
{% endblock %}
{% block js %}
<script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
<script>
        var FOLDER_URL = "{% url 'websass:file' project_id=request.tracer.project.id %}";
        var FILE_DELETE_URL = "{% url 'websass:file_delete' project_id=request.tracer.project.id %}";
        var COS_CREDENTIAL = "{% url 'websass:cos_credentials' project_id=request.tracer.project.id %}";
        var FILE_POST = "{% url 'websass:file_post' project_id=request.tracer.project.id %}";
        var CURRENT_FOLDER_ID = "{{ folder_object.id }}"

        $(function(){
        initAddModel();
        bindModelSubmit();
        bindDeleteSubmit();
        bindUploadFile();
        });
        function bindDeleteSubmit(){
            $('#btnDelete').click(function(){
                $.ajax({
                    url:FILE_DELETE_URL,
                    type:"GET",
                    data:{fid:$(this).attr('fid')},
                    success:function(res){
                        if(res.status){
                            location.href=location.href
                        }
                    }
                })
            })
        }
        function bindUploadFile(){
            $('#uploadFile').change(function(){
                $("#progressList").empty();
                var fileList=$(this)[0].files; // 把选中的文件给取到
                var FileDate_list=[]
                $.each(fileList,function(index,fileObject){
                   FileDate_list.push({'name':fileObject.name,'size':fileObject.size})

                });

                //通过js获取临时凭证
                // 初始化实例
                var COS_OBJECT = new COS({
                    getAuthorization: function (options, callback) {
                        // 异步获取临时密钥
                        $.post(COS_CREDENTIAL, JSON.stringify(FileDate_list), function (res) {
                            if(res.status){
                                var credentials = res.data && res.data.credentials;
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                                    StartTime: res.data.startTime, // 时间戳，单位秒，如：1580000000
                                    ExpiredTime: res.data.expiredTime, // 时间戳，单位秒，如：1580000900
                                });

                                $('#uploadProgress').removeClass('hide');
                            }else{
                                alert(res.error);
                            }
                        });
                    }
                });
                $.each(fileList,function(index,fileObject){
                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;
                    var key ='{{ request.tracer.project.p_name }}' + (new Date()).getTime() + Math.random() + "_" + fileName;
                    // 把上传文件放在那个progressList这个id属性里面，但是要克隆
                    var tr =$('#progressTemplate').find('tr').clone();
                    tr.find('.name').text(fileName);
                    $('#progressList').append(tr);
                    COS_OBJECT.putObject({
                            Bucket: '{{request.tracer.project.bucket}}', /* 必须 */
                            Region: '{{request.tracer.project.region}}',     /* 存储桶所在地域，必须字段 */
                            Key: key,              /* 必须 */
                            Body: fileObject, // 上传文件对象
                            onProgress: function(progressData) {
                                var percent = progressData.percent * 100 + '%'
                                tr.find('.progress-bar').text(percent);
                                tr.find('.progress-bar').css('width',percent)
                            }
                        }, function(err, data) {
                            console.log(err || data);
                            if (data && data.statusCode===200){

                                $.post(FILE_POST, {
                                    name: fileName,
                                    key: key,
                                    file_size: fileSize,
                                    parent : CURRENT_FOLDER_ID,
                                    etag: data.ETag,
                                    file_path: data.Location,
                                }, function(res){
                                        console.log(res)
                                        // 在数据库中写入数据成功，将已添加的数据在页面上动态展示
                                        var newTr = $('#rowTpl').find('tr').clone();
                                        newTr.find('.name').text(res.data.name);
                                        newTr.find('.file_size').text(res.data.file_size);
                                        newTr.find('.username').text(res.data.update_user);
                                        newTr.find('.datetime').text(res.data.datetime);
                                        newTr.find('.delete').attr('data-fid',res.data.fid)
                                        newTr.find('.download').attr('href',res.data.download_url)
                                        $("#rowList").append(newTr);
                                        tr.remove();

                                })

                            }else{
                             tr.find(".progress-error").text("上传失败:" + err)
                            }

                        });

                    });

            });
        }
        function initAddModel(){
            $('#addModal').on('show.bs.modal', function (event) {
                  var button = $(event.relatedTarget); // Button that triggered the modal
                  var recipient = button.data('whatever'); // Extract info from data-* attributes
                  var name = button.data('name'); // Extract info from data-* attributes
                  var fid = button.data('fid'); // Extract info from data-* attributes
                  var modal = $(this);
                  modal.find('.modal-title').text(recipient);
                  //如果fid存在就代表是编辑输入框
                  if(fid){
                  modal.find('#fid').val(fid);
                  modal.find('#id_name').val(name);
                  }else{
                  //让错误信息清空
                  modal.find('.error-msg').empty();
                    //document.getElementById('form').reset()//dome对象，我们也可以转换成jquery
                  $("#form")[0].reset();
                  }
            })
            $('#alertModal').on('show.bs.modal', function (event) {
              var button = $(event.relatedTarget); // Button that triggered the modal
              var fid = button.data('fid'); // Extract info from data-* attributes
              $('#btnDelete').attr('fid',fid)


            })
        }

        function bindModelSubmit(){
            $("#btnFormSubmit").click(function(){
                $.ajax({
                    url:location.href,
                    type:"POST",
                    data:$("#form").serialize(),
                    dataType:"JSON",
                    success:function(res){
                        if(res.status){
                            console.log(res)
                            //正确
                            location.href = location.href;
                        }else{
                            // 错误信息
                            console.log(res);
                            $.each(res.error, function (key, value) {
                                $("#id_" + key).next().text(value[0]);
                            })
                        }
                    }
                })
            })
        }









</script>
{% endblock %}